package com.aatrox.bhsypro.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class CookieUtil {

    public static String getCookieValue(HttpServletRequest request,String cookieName){
        return getCookieValue(request,cookieName,false);
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName, boolean b) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookieName == null){
            return null;
        }
        String reValue = null;
        try {
            for (int i = 0; i < cookies.length ; i++) {
                if (cookies[i].getName().equals(cookieName)){
                    if (b){
                        reValue = URLDecoder.decode(cookies[i].getValue(),"UTF-8");
                    }else {
                        reValue = cookies[i].getValue();
                    }
                    break;
                }
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return reValue;
    }
    /**
     * 得到cookie值
     */
    public static String getCookieValue(HttpServletRequest request,String cookieName,String encodeString){
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null|| cookieName == null){
            return null;
        }
        String retValue = null;
        try {
            for (int i = 0; i < cookieList.length ; i++) {
                if (cookieList[i].getName().equals(cookieName)){
                    retValue = URLDecoder.decode(cookieList[i].getValue(),encodeString);
                    break;
                }
            }
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return retValue;
    }

    /**
     * 设置cookie的值
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,String cookieValue){
        setCookie(request,response,cookieName,cookieValue,-1);
    }
    /**
     * 设置Cookie的值 在知道时间内生效 但不编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,String cookieValue,int cookieMaxage){
        setCookie(request,response,cookieName,cookieValue,false);
    }
    /**
     * 设置cookie的值 但不设置生效时间 但编码
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,String cookieValue,boolean isEncode) {
        setCookie(request, response, cookieName, cookieValue, -1, isEncode);
    }

    /**
     * 设置cookie的值 在指定时间内生效 编码参数(知道编码)
     * @param request
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param isEncode
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response,String cookieName,String cookieValue,int cookieMaxage,boolean isEncode) {
        doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
    }
    /**
     * 删除Cookie带cookie域名
     */
    public static void deleteCookie(HttpServletRequest request,HttpServletResponse response,String cookieName){
        doSetCookie(request,response,cookieName,"",-1,false);
    }

    /**
     * 设置Cookie的值,并使其在指定时间内生效
     */
    private static final void doSetCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,String cookieValue,int cookMaxage,boolean isEncode){
        try {
            if (cookieValue == null){
                cookieValue = "";
            }else if (isEncode){
                cookieValue = URLDecoder.decode(cookieValue,"utf-8");
            }
            Cookie cookie = new Cookie(cookieName,cookieValue);
            if (cookMaxage>0){
                cookie.setMaxAge(cookMaxage);
            }
            if (null != request){
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)){
                    cookie.setDomain(domainName);
                }
            }
            cookie.setPath("/");
            response.addCookie(cookie);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 设置 Cookie的值 并使其在指定时间内生效
     * @param request
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param cookieMaxage
     * @param encodeString
     */
    private static final void doSetCookie(HttpServletRequest request,HttpServletResponse response,String cookieName,String cookieValue,int cookieMaxage,String encodeString){
          try{
            if (cookieValue == null){
                cookieValue = "";
            }else {
                cookieValue = URLEncoder.encode(cookieValue,encodeString);
            }
            Cookie cookie = new Cookie(cookieName,cookieValue);
            if (cookieMaxage>0){
                cookie.setMaxAge(cookieMaxage);
            }
            if (null!=request){
                String domainName = getDomainName(request);
                System.out.println(domainName);
                if (!"localhost".equals(domainName)) {
                    cookie.setDomain(domainName);
                }
            }
        } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          }
    }

    /**
     * 得到cookie的域名
     */
    private static final String getDomainName(HttpServletRequest request){
        String domainName = null;
        //通过request 对象获取访问的url地址
        String serverName = request.getRequestURI().toString();
        System.out.println("{之前}"+serverName);
        if (serverName==null || serverName.equals("")){
            domainName = "";
        }else {
            //将url地址转换为小写
            serverName = serverName.toLowerCase();
            //如果url地址是以http://开头 将http://截取
            if (serverName.startsWith("http://")){
                serverName = serverName.substring(7);
            }
            int end = serverName.length();
            //判断url地址是否包含"/"
            if (serverName.contains("/")){
                //得到第一个"/"出现的位置
                end = serverName.indexOf("/");
            }
            //截取
            serverName = serverName.substring(0,end);
            //根据"."进行分割
            final String[] domains = serverName.split("\\.");
            int len = domains.length;
            if (len>3){
                //www.xxx.com.cn
                domainName = domains[len-3]+"."+domains[len-2]+"."+domains[len-1];
            }else if (len <=3 && len > 1){
                //xxx.com or xxx.cn
                domainName = domains[len-2]+"."+domains[len-1];
            }else {
                domainName = serverName;
            }
        }
        if (domainName != null && domainName.indexOf(":") > 0){
            String[] ary = domainName.split("\\:");
            domainName = ary[0];
        }
        System.out.print("{之后}"+domainName);
        return domainName;
    }
}
